'use strict';

const Controller = require('egg').Controller;
class AdController extends Controller {

  // 新增广告
  async addAd() {
    const { ctx } = this;
    try {
      ctx.validate({
        image_url: { type: 'string', reuqired: true },
        link_type: { type: 'int', required: true },
        enabled: { type: 'int', reuqired: true },
        end_time: { type: 'string', reuqired: true },
      }, ctx.request.body);
      const data = ctx.request.body;
      if (!data.goods_id) {
        delete data.goods_id;
      }
      data.end_time = parseInt(+new Date(data.end_time) / 1000);
      const res = await ctx.service.ad.addAd(data);
      if (res.code === 0) {
        ctx.status = 200;
        ctx.body = {
          code: 0,
          data: res.data,
        };
      } else if (res.code === 1) {
        ctx.status = 200;
        ctx.body = {
          code: 1,
          msg: '该商品上已经绑定了广告',
        };
      } else {
        ctx.status = 500;
        ctx.body = {
          code: -1,
          msg: '服务器报错',
        };
      }
    } catch (error) {
      console.log('error:', error);
      ctx.status = 400;
      ctx.body = {
        code: -1,
        msg: '请求的参数有误',
      };
    }
  }

  async getAdList() {
    const { ctx } = this;
    const res = await ctx.service.ad.getAdList(ctx.query);
    ctx.status = 200;
    ctx.body = {
      code: 0,
      data: res,
    };
  }

  async updateAd() {
    const { ctx } = this;
    const res = await ctx.service.ad.updateAd(ctx.request.body);
    if (res.code === 0) {
      ctx.status = 200;
      ctx.body = {
        code: 0,
        msg: '更新成功',
      };
    } else {
      ctx.status = 200;
      ctx.body = {
        code: -1,
        msg: '更新失败',
      };
    }
  }

  async getAdById() {
    const { ctx } = this;
    const res = await ctx.service.ad.getAdById(ctx.query.id);
    if (res) {
      ctx.status = 200;
      ctx.body = {
        code: 0,
        data: res,
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        code: -1,
        msg: '获取id失败',
      };
    }
  }
  // 删除
  async deleteAd() {
    const { ctx } = this;
    const res = await ctx.service.ad.deleteAd(ctx.request.body.id);
    if (res.code === 0) {
      ctx.status = 200;
      ctx.body = {
        code: 0,
        msg: '删除成功',
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        code: -1,
        msg: '删除失败',
      };
    }
  }
}

module.exports = AdController;
